<template>
  <div>
    <el-dialog
      :title="title"
      :visible.sync="dialogVisible"
      :modal="true"
      :appendToBody="true"
      width="60%"
      v-dialog-drag
      :close-on-click-modal="false"
      top="5vh"
      @close="handleClose()"
      @open="handleOpen()"
    >
      <PartitionTitle title="基础信息"></PartitionTitle>
      <el-form
        :model="form"
        :rules="rules"
        ref="ruleForm"
        label-width="120px"
        :disabled="!canEdit"
      >
        <el-form-item label="产线编码" prop="erpProductionLineCode">
          <el-input
            type="text"
            v-model="form.erpProductionLineCode"
            placeholder="请输入产线编码"
            disabled
          ></el-input>
        </el-form-item>
        <el-form-item label="产线名称" prop="erpProductionLineName">
          <el-input
            type="text"
            v-model="form.erpProductionLineName"
            placeholder="请输入产线名称"
            disabled
          ></el-input>
        </el-form-item>
        <el-form-item label="所属工厂" prop="factoryDeptName">
          <el-input
            type="text"
            v-model="form.factoryDeptName"
            placeholder="请输入所属工厂"
            disabled
          ></el-input>
        </el-form-item>
        <el-form-item label="产线负责人" prop="lineHeadRealnames">
          <el-input
            v-model="form.lineHeadRealnames"
            placeholder="请输入内容"
            size="small"
          >
            <el-button
              slot="append"
              icon="el-icon-search"
              @click="openUserDialog('lineHeadUsernames')"
            ></el-button>
          </el-input>
        </el-form-item>
        <el-form-item label="所属车间" prop="workshopName">
          <el-input
            type="text"
            v-model="form.workshopName"
            placeholder="请输入所属车间"
            disabled
          ></el-input>
        </el-form-item>
      </el-form>
      <!-- <PartitionTitle title="产线成员"></PartitionTitle>
      <div class="tool-bar" v-if="canEdit">
        <el-button
          type="primary"
          size="small"
          @click="openUserDialog('lineUsers')"
          >添加</el-button
        >
        <el-button type="default" size="small" @click="removeUser"
          >移除</el-button
        >
      </div>
      <el-table
        ref="UserTable"
        :data="form.lineUsers"
        :resizable="false"
        style="width: 100%"
      >
        <el-table-column type="selection" v-if="canEdit"> </el-table-column>
        <el-table-column type="index" width="100" label="序号">
        </el-table-column>
        <el-table-column prop="realname" label="成员名称"> </el-table-column>
        <el-table-column prop="username" label="用户名"> </el-table-column>
        <el-table-column prop="deptName" label="所在部门"> </el-table-column>
        <el-table-column prop="workStationNames" label="工位"> </el-table-column>
        <el-table-column prop="groupName" label="所属班组"> </el-table-column>
      </el-table> -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button
          v-if="canEdit"
          type="primary"
          :loading="saveloading"
          @click="handleSubmit"
          >确 定</el-button
        >
      </span>
    </el-dialog>
    <userList
      :visibles.sync="userDialog.visible"
      :multiple="true"
      :defaultValues="userDialog.defaultLineUsers"
      :selectableCallBack="selectableUserCallBack"
      :branchinnercode="rowBranchinnercode"
      @closeDialog="closeUserDialog"
    ></userList>
  </div>
</template>
<script>
import {
  getDetailWithUserInfo,
  updateUserInfo,
  getUnSelectableUsernamesByWorkshopCode,
} from "@/api/prodLineMgmt/productionLineUser";
import { checkPermi } from "@/utils/permission";
export default {
  props: {
    visible: {
      type: Boolean,
      default: false,
    },
    row: {
      type: Object,
      default: null,
    },
    disabled: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    return {
      form: {
        id: null,
        erpProductionLineCode: null,
        erpProductionLineName: null,
        deptId: null,
        factoryDeptName: null,
        lineHeadUsernames: null,
        lineHeadRealnames: null,
        workshopCode: null,
        workshopName: null,
        // lineUsers: [],
      },
      rules: {
        lineHeadRealnames: [
          { required: true, message: "请选择产线负责人", trigger: "change" },
        ],
      },
      saveloading: false,
      userDialog: {
        visible: false,
        key: null,
        defaultLineUsers: [],
      },
      disabledUser: [],
      selectableUserCallBack: (row) => {
        return !this.disabledUser.includes(row.username);
      },
    };
  },
  computed: {
    dialogVisible: {
      set(val) {
        this.$emit("update:visible", val);
      },
      get() {
        return this.visible;
      },
    },
    title() {
      if (this.disabled == true) {
        return '产线负责人详情'
      }
      if (!!this.row) {
        return '编辑产线负责人'
      }
      return '新增产线负责人'
    },
    rowBranchinnercode() {
      return this.form?.deptId || null;
    },
    canEdit() {
      if (this.disabled == true) {
        return false;
      }
      if (this.row?.id) {
        return checkPermi(["prodLineMgmt:productionLineUser:edit"]);
      }
      return true;
    },
  },
  methods: {
    handleClose() {
      this.saveloading = false;
      this.resetFormData();
    },
    handleOpen() {
      this.getDetail();
    },
    // 获取详情
    getDetail() {
      if (!this.row?.id) {
        return;
      }
      getDetailWithUserInfo(this.row.id)
        .then((res) => {
          if (res.code == 200 && res.data) {
            const {
              id,
              erpProductionLineCode,
              erpProductionLineName,
              bizDeptVo,
              lineHeadUsernames,
              lineHeadRealnames,
              workshopCode,
              workshopDto,
              // lineUsers,
            } = res.data;
            this.form = {
              id,
              erpProductionLineCode,
              erpProductionLineName,
              deptId: bizDeptVo?.deptId,
              factoryDeptName: bizDeptVo?.deptName,
              lineHeadUsernames,
              lineHeadRealnames,
              workshopCode,
              workshopName: workshopDto?.workshopName,
              // lineUsers,
            };
            this.$nextTick(() => {
              this.$refs.ruleForm?.clearValidate();
            });
          }
        })
        .catch(() => {});
    },
    handleSubmit() {
      if (!this.canEdit) {
        return;
      }
      this.saveloading = true;
      this.$refs.ruleForm.validate((flag) => {
        if (flag && !this.monthError) {
          const { id, lineHeadUsernames } = this.form;
          const param = {
            id,
            lineHeadUsernames,
          };
          updateUserInfo(param)
            .then((res) => {
              if (res.code == 200) {
                this.msgSuccess(id ? "修改成功！" : "新增成功！");
                this.$emit("submit-success");
                this.dialogVisible = false;
              }
              this.saveloading = false;
            })
            .catch(() => {
              this.saveloading = false;
            });
        } else {
          this.saveloading = false;
        }
      });
    },
    resetFormData() {
      this.$refs.ruleForm?.resetFields();
      this.form = {
        id: null,
        erpProductionLineCode: null,
        erpProductionLineName: null,
        deptId: null,
        factoryDeptName: null,
        lineHeadUsernames: null,
        lineHeadRealnames: null,
        workshopCode: null,
        workshopName: null,
        // lineUsers: [],
      };
    },
    openUserDialog(key) {
      getUnSelectableUsernamesByWorkshopCode(this.form.workshopCode).then(
        (res) => {
          this.disabledUser = res.data;
        }
      );

      this.userDialog.visible = true;
      this.userDialog.key = key;
      if (key === "lineUsers") {
        this.userDialog.defaultLineUsers = this.form.lineUsers;
      } else if (key === "lineHeadUsernames") {
        const { lineHeadUsernames, lineHeadRealnames } = this.form;

        const _lineHeadUsernames = lineHeadUsernames
          ? lineHeadUsernames?.split(",")
          : [];
        const _lineHeadRealnames = lineHeadRealnames
          ? lineHeadRealnames?.split(",")
          : [];

        let _defaultLineUsers = [];
        _lineHeadUsernames.forEach((ele, i) => {
          _defaultLineUsers.push({
            username: ele,
            realname: _lineHeadRealnames[i],
          });
        });
        this.userDialog.defaultLineUsers = _defaultLineUsers;
      }
    },
    closeUserDialog(list) {
      switch (this.userDialog.key) {
        case "lineHeadUsernames":
          this.form.lineHeadUsernames = list
            .map((ele) => ele.username)
            .join(",");
          this.form.lineHeadRealnames = list
            .map((ele) => ele.realname)
            .join(",");
          break;
        case "lineUsers":
          this.form.lineUsers = list.map((ele) => {
            return {
              realname: ele.realname,
              username: ele.username,
              deptName: ele.dept?.name || ele.deptName,
              workStationNames: ele.bizUserVo?.workStationNames || ele.workStationNames,
              groupName: ele.bizUserVo?.groupName || ele.groupName,
            };
          });
          break;
        default:
          break;
      }
    },
    // removeUser() {
    //   const usernames = this.$refs.UserTable.selection.map(
    //     (ele) => ele.username
    //   );
    //   this.form.lineUsers = this.form.lineUsers.filter(
    //     (ele) => !usernames.includes(ele.username)
    //   );
    // },
  },
  watch: {},
};
</script>
<style lang="scss" scoped>
.el-form {
  display: flex;
  justify-content: space-between;
  flex-flow: wrap;
  .el-form-item {
    width: 49%;
  }
  .el-date-editor.el-input,
  .el-select {
    width: 100%;
  }
}
.tool-bar {
  margin-bottom: 10px;
}
</style>
